import App from './App.vue';
import util from '@/common/globalProperties';
import { createSSRApp } from 'vue';
import * as Pinia from 'pinia';
import { i18nInit, baseInit, endlessUiInit, mixinInit } from '@/common/init';
import { setRequestHeader } from '@/common/request';
import './typings/index.d.ts';

// #ifdef MP-WEIXIN
import '@/common/init/mpApp';
// #endif
// #ifdef MP-ALIPAY
import '@/common/init/aliApp';
// #endif
// #ifdef HTML5 || PREVIEW
import h5Init from '@/common/init/h5';
// #endif
// #ifdef APP-PLUS
import appInit from '@/common/init/app';
// #endif
// #ifdef PRIVATE || SUBSCRIPTION
import {getQueryString} from '@/common/wxInit'
// 公众号与私域的初始化
import '@/common/init/mp'
// #endif
// 清空推荐码，防止存在遗留导致推荐关系错乱
uni.removeStorageSync('userSalt');
// #ifdef H5
if (!import.meta.env.DEV) {
	const [pageUrl, scene] = (window.location.href.split('#')[1] || '').split('?');
	// h5先跳转splash页面，初始化完成后再返回原页面
	if (pageUrl && !['/pages/splash','/pages/public/account/binding', '/'].includes(pageUrl)) {
		let hasReset = true
		// #ifdef PRIVATE || SUBSCRIPTION
		if(getQueryString('code')){
			hasReset = false
		}
		// #endif
		if(hasReset)
		window.location.href = `${window.location.href.split('#')[0]}#/pages/splash?url=${encodeURIComponent(pageUrl)}${scene ? `&scene=${encodeURIComponent(scene)}` : ''}`;
	}
}

// #endif

// #ifdef APP-PLUS
uni.setStorageSync('tenant', import.meta.env.VITE_APP_TENANT);
appInit();
// #endif

// #ifdef  APP-PLUS||MP-WEIXIN||MP-ALIPAY
(function (global: any) {
	/**
	 * 兼容TextDecoder
	 */
	if (typeof global.TextDecoder !== 'function') {
		function _TextDecoder() {}
		_TextDecoder.prototype.decode = function (arrayBuffer: Uint8Array) {
			return decodeURIComponent(escape(String.fromCharCode.apply(null, new Uint8Array(arrayBuffer))));
		};
		global.TextDecoder = _TextDecoder;
	}
	if (typeof global.TextEncoder !== 'function') {
		function _TextEncoder() {}
		_TextEncoder.prototype.encode = function (str: string) {
			var data = unescape(encodeURIComponent(str))
				.split('')
				.map((val) => val.charCodeAt(0));
			return typeof Uint8Array == 'function' ? new Uint8Array(data) : data;
		};
		// @ts-ignore
		global.TextEncoder = _TextEncoder;
	}
})(this || window || globalThis);

// #endif

// 设置全局请求头，所有http请求必须在此函数后执行
setRequestHeader();

// #ifdef HTML5 || PREVIEW
await h5Init();
setRequestHeader();
baseInit();
// #endif

// #ifdef  PRIVATE || SUBSCRIPTION
baseInit();
setRequestHeader();
// #endif

export function createApp() {
	const app = createSSRApp(App);
	app.use(Pinia.createPinia());
	endlessUiInit(app);
	i18nInit(app);
	mixinInit(app);
	util.install(app.config);
	// #ifdef  MP-WEIXIN ||MP-ALIPAY|| APP
	baseInit();
	// #endif

	return {
		app,
		Pinia
	};
}
